package com.hrh.selectsystem.aop;

import cn.hutool.core.text.CharSequenceUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.hrh.selectsystem.annotation.PassToken;
import com.hrh.selectsystem.common.ErrorCode;
import com.hrh.selectsystem.common.ResultUtils;
import com.hrh.selectsystem.exception.BusinessException;
import com.hrh.selectsystem.model.entity.Admin;
import com.hrh.selectsystem.model.entity.Mentor;
import com.hrh.selectsystem.model.entity.Student;
import com.hrh.selectsystem.service.MentorService;
import com.hrh.selectsystem.service.impl.AdminServiceImpl;
import com.hrh.selectsystem.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author hrh
 * 获取token并验证
 */
@Component
public class MyJwtInterceptor implements HandlerInterceptor {
    @Resource
    private AdminServiceImpl adminService;
    @Resource
    private StudentServiceImpl studentService;
    @Resource
    private MentorService mentorService;

    /**
     * 拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        // 获取token
        String token = request.getHeader("token");
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //检查是否通过有PassToken注解
        if (method.isAnnotationPresent(PassToken.class)) {
            //如果有则跳过认证检查
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //否则进行token检查
        if (CharSequenceUtil.isBlank(token)) {
            throw new BusinessException(ErrorCode.NO_TOKEN, "token不存在");
        }
        //获取token中的用户id
        String userId;
        try {
            userId = getUserIdFromToken(token);
        } catch (JWTDecodeException j) {
            throw new BusinessException(ErrorCode.TOKEN_ERROR, "token验证失败");
        }
        //获取token中的用户权限
        String userRole = getUserRoleFromToken(token);
        if (CharSequenceUtil.isBlank(userRole)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无token权限");
        }
        //检查token权限
        if (!userRole.equals("admin") && !userRole.equals("student") && !userRole.equals("mentor")) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        //如果权限为管理员
        if (userRole.equals("admin")) {
            Admin admin = adminService.getById(userId);
            if (admin == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
            }
            //验证token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getAdminpassword())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new BusinessException(406, "权限验证失败！");
            }
            //检查路径
            if (requestURI.startsWith("/api/student/") || requestURI.startsWith("/api/mentor/")) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该路径");
            }
        }
        //如果权限为学生
        if (userRole.equals("student")){
            Student student = studentService.getById(userId);
            if (student == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
            }
            //验证token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(student.getStudentpassword())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new BusinessException(406, "权限验证失败！");
            }
            //检查路径
            if (requestURI.startsWith("/api/admin/") || requestURI.startsWith("/api/mentor/")) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该路径");
            }
        }
        //如果权限为导师
        if (userRole.equals("mentor")){
            Mentor mentor = mentorService.getById(userId);
            if (mentor == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
            }
            //验证token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(mentor.getMentorpassword())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new BusinessException(406, "权限验证失败！");
            }
            //检查路径
            if (requestURI.startsWith("/api/admin/") || requestURI.startsWith("/api/student/")) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限访问该路径");
            }
        }

        return true;
    }

    /**
     * 解析token并获取用户id
     */
    public static String getUserIdFromToken(String token) {
        try {
            return JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException e) {
            throw new BusinessException(ErrorCode.TOKEN_ERROR, "token解析失败");
        }
    }

    /**
     * 解析token并获取用户角色
     * @param token
     * @return
     */
    public static String getUserRoleFromToken(String token) {
        try {
            return JWT.decode(token).getClaim("userRole").asString();
        } catch (JWTDecodeException e) {
            throw new BusinessException(ErrorCode.TOKEN_ERROR, "token解析失败");
        }
    }
}